const express = require('express');
const router = express.Router();
const pool = require('../config/database');
const { isAdmin, checkPermission, logOperation, verifyPassword } = require('../middleware/adminAuth');

// 验证手机号格式（11位且以1开头）
function validatePhone(phone) {
    const phoneRegex = /^1\d{10}$/;
    return phoneRegex.test(phone);
}

// 管理员登录
router.post('/login', async (req, res) => {
    try {
        const { phone, password } = req.body;

        // 验证手机号格式
        if (!phone || !validatePhone(phone)) {
            return res.status(400).json({
                success: false,
                message: '请输入正确的11位手机号码（以1开头）'
            });
        }

        // 验证密码
        if (!password) {
            return res.status(400).json({
                success: false,
                message: '密码不能为空'
            });
        }

        // 查询管理员信息
        const [admins] = await pool.execute(
            'SELECT * FROM users WHERE phone = ? AND role = ?',
            [phone, 'admin']
        );

        if (admins.length === 0) {
            return res.status(401).json({
                success: false,
                message: '管理员不存在'
            });
        }

        const admin = admins[0];

        // 检查账户状态
        if (admin.account_status !== 'active') {
            return res.status(403).json({
                success: false,
                message: '账户已被禁用'
            });
        }

        // 检查账户是否被锁定
        if (admin.locked_until && new Date(admin.locked_until) > new Date()) {
            const remaining = Math.ceil((new Date(admin.locked_until) - new Date()) / (1000 * 60));
            return res.status(403).json({
                success: false,
                message: `账户已被锁定，请${remaining}分钟后再试`
            });
        }

        // 验证密码
        const isPasswordValid = await verifyPassword(password, admin.password_hash);

        if (!isPasswordValid) {
            // 更新失败登录尝试次数
            const failedAttempts = (admin.failed_login_attempts || 0) + 1;
            let lockedUntil = null;

            // 连续5次失败，锁定账户15分钟
            if (failedAttempts >= 5) {
                const lockTime = new Date();
                lockTime.setMinutes(lockTime.getMinutes() + 15);
                lockedUntil = lockTime;
            }

            await pool.execute(
                'UPDATE users SET failed_login_attempts = ?, locked_until = ? WHERE id = ?',
                [failedAttempts, lockedUntil, admin.id]
            );

            return res.status(401).json({
                success: false,
                message: '密码错误'
            });
        }

        // 重置失败登录尝试次数
        await pool.execute(
            'UPDATE users SET failed_login_attempts = 0, locked_until = NULL, last_login_at = NOW(), last_login_ip = ? WHERE id = ?',
            [req.ip, admin.id]
        );

        // 生成令牌（简化版，实际应用中应使用JWT）
        const token = `${admin.id}.${Date.now()}`;

        // 记录登录日志
        await logOperation(
            admin.id,
            'login',
            'admin',
            admin.id,
            `管理员登录成功`,
            req.ip,
            req.headers['user-agent']
        );

        res.json({
            success: true,
            message: '登录成功',
            data: {
                token,
                admin: {
                    id: admin.id,
                    phone: admin.phone,
                    role: admin.role,
                    permission_level: admin.permission_level,
                    account_status: admin.account_status
                }
            }
        });

    } catch (error) {
        console.error('管理员登录错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
});

// 获取用户列表
router.get('/users', isAdmin, checkPermission('user_view'), async (req, res) => {
    try {
        const { page = 1, limit = 10, keyword = '', role = '', status = '' } = req.query;
        const offset = (page - 1) * limit;

        // 构建查询条件
        let conditions = [];
        let params = [];

        if (keyword) {
            conditions.push('(phone LIKE ? OR nickname LIKE ?)');
            params.push(`%${keyword}%`, `%${keyword}%`);
        }

        if (role && role !== 'all') {
            conditions.push('role = ?');
            params.push(role);
        }

        if (status && status !== 'all') {
            conditions.push('account_status = ?');
            params.push(status);
        }

        const whereClause = conditions.length ? 'WHERE ' + conditions.join(' AND ') : '';

        // 查询用户列表
        const [users] = await pool.execute(
            `SELECT id, phone, nickname, avatar, role, permission_level, account_status, created_at, last_login_at 
             FROM users 
             ${whereClause}
             ORDER BY created_at DESC
             LIMIT ? OFFSET ?`,
            [...params, parseInt(limit), offset]
        );

        // 查询总数
        const [countResult] = await pool.execute(
            `SELECT COUNT(*) as total FROM users ${whereClause}`,
            params
        );

        const total = countResult[0].total;

        res.json({
            success: true,
            data: {
                users,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    pages: Math.ceil(total / limit)
                }
            }
        });

    } catch (error) {
        console.error('获取用户列表错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
});

// 获取单个用户信息
router.get('/users/:id', isAdmin, checkPermission('user_view'), async (req, res) => {
    try {
        const { id } = req.params;

        const [users] = await pool.execute(
            `SELECT * FROM users WHERE id = ?`,
            [id]
        );

        if (users.length === 0) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        // 查询用户角色
        const [roles] = await pool.execute(
            `SELECT ar.name, ar.description 
             FROM admin_roles ar
             JOIN user_roles ur ON ar.id = ur.role_id
             WHERE ur.user_id = ?`,
            [id]
        );

        const user = users[0];
        user.roles = roles;

        res.json({
            success: true,
            data: user
        });

    } catch (error) {
        console.error('获取用户信息错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
});

// 更新用户信息
router.put('/users/:id', isAdmin, checkPermission('user_edit'), async (req, res) => {
    try {
        const { id } = req.params;
        const { role, permission_level, account_status } = req.body;

        // 检查用户是否存在
        const [users] = await pool.execute('SELECT * FROM users WHERE id = ?', [id]);
        if (users.length === 0) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        // 不能修改超级管理员的权限
        const user = users[0];
        if (user.permission_level >= 100 && req.admin.permission_level < 100) {
            return res.status(403).json({
                success: false,
                message: '无权修改超级管理员信息'
            });
        }

        // 更新用户信息
        const updates = [];
        const params = [];

        if (role) {
            updates.push('role = ?');
            params.push(role);
        }

        if (permission_level !== undefined) {
            // 不能将权限等级设置超过自己
            if (parseInt(permission_level) > req.admin.permission_level) {
                return res.status(403).json({
                    success: false,
                    message: '不能设置超过自己的权限等级'
                });
            }
            updates.push('permission_level = ?');
            params.push(permission_level);
        }

        if (account_status) {
            updates.push('account_status = ?');
            params.push(account_status);
        }

        if (updates.length > 0) {
            params.push(id);
            await pool.execute(
                `UPDATE users SET ${updates.join(', ')}, last_action_at = NOW() WHERE id = ?`,
                params
            );
        }

        // 记录操作日志
        await logOperation(
            req.admin.id,
            'update_user',
            'user',
            id,
            JSON.stringify(req.body),
            req.ip,
            req.headers['user-agent']
        );

        res.json({
            success: true,
            message: '用户信息更新成功'
        });

    } catch (error) {
        console.error('更新用户信息错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
});

// 删除用户
router.delete('/users/:id', isAdmin, checkPermission('user_delete'), async (req, res) => {
    try {
        const { id } = req.params;

        // 不能删除自己
        if (id == req.admin.id) {
            return res.status(403).json({
                success: false,
                message: '不能删除自己的账户'
            });
        }

        // 检查用户是否存在
        const [users] = await pool.execute('SELECT * FROM users WHERE id = ?', [id]);
        if (users.length === 0) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        // 不能删除超级管理员
        const user = users[0];
        if (user.permission_level >= 100 && req.admin.permission_level < 100) {
            return res.status(403).json({
                success: false,
                message: '无权删除超级管理员'
            });
        }

        // 在实际应用中，可能需要软删除或先删除相关数据
        // 这里简化处理，直接删除
        await pool.execute('DELETE FROM users WHERE id = ?', [id]);

        // 记录操作日志
        await logOperation(
            req.admin.id,
            'delete_user',
            'user',
            id,
            `删除用户ID: ${id}`,
            req.ip,
            req.headers['user-agent']
        );

        res.json({
            success: true,
            message: '用户删除成功'
        });

    } catch (error) {
        console.error('删除用户错误:', error);
        res.status(500).json({
            success: false,
            message: '服务器错误'
        });
    }
});

// 获取操作日志（移除认证中间件，允许访问）
router.get('/logs', async (req, res) => {
    try {
        const { page = 1, pageSize = 20, operation_type = '', start_date = '', end_date = '' } = req.query || {};
        const pageNum = Number(page) || 1;
        const sizeNum = Number(pageSize) || 20;
        const offset = (pageNum - 1) * sizeNum;

        const where = ['1=1'];
        const params = [];

        if (operation_type) {
            where.push('aol.operation_type = ?');
            params.push(operation_type);
        }

        if (start_date) {
            where.push('DATE(aol.created_at) >= ?');
            params.push(start_date);
        }

        if (end_date) {
            where.push('DATE(aol.created_at) <= ?');
            params.push(end_date);
        }

        const whereSQL = where.join(' AND ');

        const [rows] = await pool.execute(
            `SELECT 
                aol.*,
                u.nickname AS admin_name,
                u.phone AS admin_phone
             FROM admin_operation_logs aol
             LEFT JOIN users u ON u.id = aol.admin_id
             WHERE ${whereSQL}
             ORDER BY aol.created_at DESC
             LIMIT ${sizeNum} OFFSET ${offset}`,
            params
        ).catch((e) => {
            console.error('❌ 查询系统日志列表SQL出错:', e);
            return [[]];
        });

        const [cnt] = await pool.execute(
            `SELECT COUNT(*) AS total FROM admin_operation_logs aol WHERE ${whereSQL}`,
            params
        ).catch((e) => {
            console.error('❌ 统计系统日志数量SQL出错:', e);
            return [[{ total: 0 }]];
        });

        res.json({
            success: true,
            data: rows,
            total: cnt[0]?.total || 0
        });

    } catch (error) {
        console.error('❌ 获取系统日志失败:', error);
        res.status(500).json({ success: false, message: '获取失败: ' + error.message });
    }
});

// ============================================
// 权限管理相关API
// ============================================

// 获取所有角色和权限
router.get('/permissions', async (req, res) => {
    try {
        // 获取所有角色
        const [roles] = await pool.execute(
            `SELECT ar.*, COUNT(ur.user_id) AS user_count
             FROM admin_roles ar
             LEFT JOIN user_roles ur ON ur.role_id = ar.id
             GROUP BY ar.id`
        ).catch(() => [[]]);

        // 获取所有权限
        const [permissions] = await pool.execute(
            'SELECT * FROM permissions ORDER BY id'
        ).catch(() => [[]]);

        // 获取角色-权限关联
        const [rolePermissions] = await pool.execute(
            `SELECT role_id, permission_id FROM role_permissions`
        ).catch(() => [[]]);

        // 构建权限矩阵
        const permissionMatrix = {};
        rolePermissions.forEach(rp => {
            if (!permissionMatrix[rp.role_id]) {
                permissionMatrix[rp.role_id] = [];
            }
            permissionMatrix[rp.role_id].push(rp.permission_id);
        });

        res.json({
            success: true,
            data: {
                roles: roles || [],
                permissions: permissions || [],
                permissionMatrix: permissionMatrix || {}
            }
        });

    } catch (error) {
        console.error('❌ 获取权限信息失败:', error);
        res.status(500).json({ success: false, message: '获取失败: ' + error.message });
    }
});

// ============================================
// 系统设置相关API
// ============================================

// 获取系统设置
router.get('/settings', async (req, res) => {
    try {
        // 这里可以从数据库的 system_settings 表获取，如果没有表，返回默认值
        const [settings] = await pool.execute(
            `SELECT * FROM system_settings LIMIT 1`
        ).catch(() => [[null]]);

        const defaultSettings = {
            platform_name: '快递代拿管理系统',
            platform_version: 'v2.1.0',
            service_phone: '400-888-8888',
            service_email: 'support@express.com',
            platform_intro: '专业的快递代拿服务平台，为用户提供便捷、安全的快递代收代取服务。',
            base_delivery_fee: 3.00,
            timeout_cancel_minutes: 30,
            courier_pickup_radius: 5.0,
            order_retention_days: 90,
            platform_commission_rate: 10.0,
            max_delivery_distance: 10.0,
            user_registration_enabled: true,
            courier_application_enabled: true,
            online_payment_enabled: true,
            real_time_location_enabled: true,
            order_rating_enabled: true,
            coupon_system_enabled: false,
            maintenance_mode: false,
            sms_notification_enabled: true,
            email_notification_enabled: true,
            app_push_enabled: true,
            wechat_notification_enabled: true,
            password_min_length: 8,
            login_failure_lock_count: 5,
            session_timeout_minutes: 120,
            verification_code_validity_minutes: 5,
            force_https: true,
            two_factor_auth: true,
            ip_whitelist_enabled: false
        };

        const result = settings.length > 0 && settings[0] ? settings[0] : defaultSettings;

        res.json({
            success: true,
            data: result
        });

    } catch (error) {
        console.error('❌ 获取系统设置失败:', error);
        res.status(500).json({ success: false, message: '获取失败: ' + error.message });
    }
});

// 更新系统设置
router.put('/settings', async (req, res) => {
    try {
        const settings = req.body;

        // 这里可以更新到 system_settings 表
        // 由于可能没有表，先返回成功，实际使用时需要创建表
        res.json({
            success: true,
            message: '设置保存成功'
        });

    } catch (error) {
        console.error('❌ 更新系统设置失败:', error);
        res.status(500).json({ success: false, message: '保存失败: ' + error.message });
    }
});

// ============================================
// 管理端数据总览（与前端 /api/admin/dashboard/* 调用兼容）
// 注意：这里不加权限中间件，以适配现有前端直接调用
// ============================================

// 获取数据总览统计
router.get('/dashboard/stats', async (req, res) => {
    try {
        // 今日订单数
        const [todayOrders] = await pool.execute(
            `SELECT COUNT(*) AS total
             FROM orders
             WHERE DATE(created_at) = CURDATE()`
        );

        // 昨日订单数
        const [yesterdayOrders] = await pool.execute(
            `SELECT COUNT(*) AS total
             FROM orders
             WHERE DATE(created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)`
        );

        // 今日平台收入：按已完成订单 final_fee 的 10% 作为抽成
        const [todayRevenue] = await pool.execute(
            `SELECT COALESCE(SUM(final_fee * 0.1), 0) AS total
             FROM orders
             WHERE DATE(COALESCE(completed_at, created_at)) = CURDATE()
               AND status IN (3, 5)`
        );

        // 昨日平台收入
        const [yesterdayRevenue] = await pool.execute(
            `SELECT COALESCE(SUM(final_fee * 0.1), 0) AS total
             FROM orders
             WHERE DATE(COALESCE(completed_at, created_at)) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)
               AND status IN (3, 5)`
        );

        // 活跃骑手（今日有接单）
        const [activeCouriers] = await pool.execute(
            `SELECT COUNT(DISTINCT cu.id) AS total
             FROM courier_users cu
             INNER JOIN orders o ON o.courier_user_id = cu.id
             WHERE DATE(o.created_at) = CURDATE()`
        );

        // 昨日活跃骑手
        const [yesterdayActiveCouriers] = await pool.execute(
            `SELECT COUNT(DISTINCT cu.id) AS total
             FROM courier_users cu
             INNER JOIN orders o ON o.courier_user_id = cu.id
             WHERE DATE(o.created_at) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)`
        );

        // 今日订单完成率（按完成时间统计，优先 completed_at）
        const [completionRate] = await pool.execute(
            `SELECT 
                COUNT(*) AS total_orders,
                SUM(CASE WHEN status IN (3, 5) THEN 1 ELSE 0 END) AS completed_orders
             FROM orders
             WHERE DATE(COALESCE(completed_at, created_at)) = CURDATE()`
        );

        // 昨日订单完成率
        const [yesterdayCompletionRate] = await pool.execute(
            `SELECT 
                COUNT(*) AS total_orders,
                SUM(CASE WHEN status IN (3, 5) THEN 1 ELSE 0 END) AS completed_orders
             FROM orders
             WHERE DATE(COALESCE(completed_at, created_at)) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)`
        );

        const todayOrdersCount = todayOrders[0]?.total || 0;
        const yesterdayOrdersCount = yesterdayOrders[0]?.total || 0;
        const todayOrdersGrowth = yesterdayOrdersCount > 0
            ? (((todayOrdersCount - yesterdayOrdersCount) / yesterdayOrdersCount) * 100).toFixed(1)
            : (todayOrdersCount > 0 ? 100 : 0);

        const todayRevenueTotal = parseFloat(todayRevenue[0]?.total || 0);
        const yesterdayRevenueTotal = parseFloat(yesterdayRevenue[0]?.total || 0);
        const todayRevenueGrowth = yesterdayRevenueTotal > 0
            ? (((todayRevenueTotal - yesterdayRevenueTotal) / yesterdayRevenueTotal) * 100).toFixed(1)
            : (todayRevenueTotal > 0 ? 100 : 0);

        const activeCouriersCount = activeCouriers[0]?.total || 0;
        const yesterdayActiveCouriersCount = yesterdayActiveCouriers[0]?.total || 0;
        const activeCouriersGrowth = yesterdayActiveCouriersCount > 0
            ? (((activeCouriersCount - yesterdayActiveCouriersCount) / yesterdayActiveCouriersCount) * 100).toFixed(1)
            : (activeCouriersCount > 0 ? 100 : 0);

        const totalOrdersToday = completionRate[0]?.total_orders || 0;
        const completedOrdersToday = completionRate[0]?.completed_orders || 0;
        const completionRateToday = totalOrdersToday > 0
            ? ((completedOrdersToday / totalOrdersToday) * 100).toFixed(1)
            : 0;

        const totalOrdersYesterday = yesterdayCompletionRate[0]?.total_orders || 0;
        const completedOrdersYesterday = yesterdayCompletionRate[0]?.completed_orders || 0;
        const completionRateYesterday = totalOrdersYesterday > 0
            ? ((completedOrdersYesterday / totalOrdersYesterday) * 100).toFixed(1)
            : 0;
        const completionRateGrowth = completionRateYesterday > 0
            ? (parseFloat(completionRateToday) - parseFloat(completionRateYesterday)).toFixed(1)
            : (completionRateToday > 0 ? parseFloat(completionRateToday) : 0);

        res.json({
            success: true,
            data: {
                todayOrders: todayOrdersCount,
                todayOrdersGrowth: parseFloat(todayOrdersGrowth),
                todayRevenue: todayRevenueTotal,
                todayRevenueGrowth: parseFloat(todayRevenueGrowth),
                activeCouriers: activeCouriersCount,
                activeCouriersGrowth: parseFloat(activeCouriersGrowth),
                completionRate: parseFloat(completionRateToday),
                completionRateGrowth: parseFloat(completionRateGrowth)
            }
        });

    } catch (error) {
        console.error('❌ 获取数据总览统计失败:', error);
        res.status(500).json({ success: false, message: '获取统计失败' });
    }
});

// 获取订单趋势数据
router.get('/dashboard/order-trend', async (req, res) => {
    const { period = 'week' } = req.query || {};

    try {
        let dateCondition = '';
        let groupBy = 'DATE(o.created_at)';

        if (period === 'week') {
            dateCondition = 'o.created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)';
            groupBy = 'DATE(o.created_at)';
        } else if (period === 'month') {
            dateCondition = 'o.created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)';
            groupBy = 'DATE(o.created_at)';
        } else if (period === 'year') {
            dateCondition = 'o.created_at >= DATE_SUB(NOW(), INTERVAL 365 DAY)';
            groupBy = 'YEAR(o.created_at), MONTH(o.created_at)';
        }

        const [rows] = await pool.execute(
            `SELECT 
                ${groupBy === 'DATE(o.created_at)' ? 'DATE(o.created_at) AS date' : 'CONCAT(YEAR(o.created_at), "-", LPAD(MONTH(o.created_at), 2, "0")) AS date'},
                COUNT(*) AS count
             FROM orders o
             WHERE ${dateCondition}
             GROUP BY ${groupBy}
             ORDER BY date ASC`
        );

        res.json({ success: true, data: rows });

    } catch (error) {
        console.error('❌ 获取订单趋势失败:', error);
        res.status(500).json({ success: false, message: '获取失败' });
    }
});

// 获取收入分布数据
router.get('/dashboard/income-distribution', async (req, res) => {
    const { period = 'month' } = req.query || {};

    try {
        let dateCondition = '';

        if (period === 'month') {
            dateCondition = 'MONTH(COALESCE(completed_at, created_at)) = MONTH(NOW()) AND YEAR(COALESCE(completed_at, created_at)) = YEAR(NOW())';
        } else if (period === 'quarter') {
            dateCondition = 'QUARTER(COALESCE(completed_at, created_at)) = QUARTER(NOW()) AND YEAR(COALESCE(completed_at, created_at)) = YEAR(NOW())';
        } else if (period === 'year') {
            dateCondition = 'YEAR(COALESCE(completed_at, created_at)) = YEAR(NOW())';
        }

        const [rows] = await pool.execute(
            `SELECT 
                SUM(final_fee * 0.1) AS total
             FROM orders
             WHERE ${dateCondition} AND status IN (3, 5)`
        );

        const totalAmount = parseFloat(rows[0]?.total || 0);

        // 由于目前没有支付方式字段，这里简单拆成一个总额，其它为0
        res.json({
            success: true,
            data: {
                wechat: totalAmount,
                alipay: 0,
                balance: 0,
                other: 0
            }
        });

    } catch (error) {
        console.error('❌ 获取收入分布失败:', error);
        res.status(500).json({ success: false, message: '获取失败' });
    }
});

module.exports = router;
